<!-- 物资设备采购策划表 -->
<template>
    <div>
      <a-card>
        <title-name title="物资设备采购策划表" />
        <a-table :columns="columns" :data-source="data" bordered :scroll="{ x: 3678 }" :pagination="false">
          <span slot="serial" slot-scope="text, record, index">{{ index + 1 }}</span>
          <!-- 物资名称 -->
          <span slot="name" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell :required="true" v-else :key="index + '-name'" :text="text" @change="onCellChange(record, 'name', $event)" :maxLength="300"></EditableCell>
          </span>
          <!-- 采购方式 -->
          <span slot="procurementMethod" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell :required="true" v-else :key="index + '-procurementMethod'" :text="text" @change="onCellChange(record, 'procurementMethod', $event)" :maxLength="300"></EditableCell>
          </span>
          <!-- 责任人及计划时间 -->
          <span slot="responsibleTime" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell :required="true" v-else :key="index + '-responsibleTime'" :text="text" @change="onCellChange(record, 'responsibleTime', $event)" :maxLength="300"></EditableCell>
          </span>
          <!-- 产运周期（天） -->
          <span slot="productionCycle" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableNumber :required="true" v-else :key="index + '-productionCycle'" :text="text" @change="onCellChange(record, 'productionCycle', $event)"></EditableNumber>
          </span>
          <!-- 最迟时间 -->
          <template slot="materialLatestTime" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableDate :required="true" v-else :key="index + '-materialLatestTime'" :text="text" @change="onCellChange(record, 'materialLatestTime', $event)"></EditableDate>
          </template>
          <!-- 责任人 -->
          <span slot="materialResponsibleId" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ record.materialResponsibleName }}</span>
            <div v-else class="requiredFormItem">
              <SelectPerson :fetching="fetching" :key="index + '-materialResponsibleId'" @changeEmployeeName="changeEmployeeName" :memberList="memberList" :record="record" bindKey="materialResponsibleId"></SelectPerson>
            </div>
          </span>
  
          <!-- 最迟时间 -->
          <template slot="tenderLatestTime" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableDate :required="true" v-else :key="index + '-tenderLatestTime'" :text="text" @change="onCellChange(record, 'tenderLatestTime', $event)"></EditableDate>
          </template>
          <!-- 责任人 -->
          <span slot="tenderResponsibleId" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ record.tenderResponsibleName }}</span>
            <div v-else class="requiredFormItem">
              <SelectPerson :fetching="fetching" :key="index + '-tenderResponsibleId'" @changeEmployeeName="changeEmployeeName" :memberList="memberList" :record="record" bindKey="tenderResponsibleId"></SelectPerson>
            </div>
          </span>
  
          <!-- 最迟时间 -->
          <template slot="brandLatestTime" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableDate :required="true" v-else :key="index + '-brandLatestTime'" :text="text" @change="onCellChange(record, 'brandLatestTime', $event)"></EditableDate>
          </template>
          <!-- 责任人 -->
          <span slot="brandResponsibleId" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ record.brandResponsibleName }}</span>
            <div v-else class="requiredFormItem">
              <SelectPerson :fetching="fetching" :key="index + '-brandResponsibleId'" @changeEmployeeName="changeEmployeeName" :memberList="memberList" :record="record" bindKey="brandResponsibleId"></SelectPerson>
            </div>
          </span>
  
          <!-- 最迟时间 -->
          <template slot="demandLatestTime" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableDate :required="true" v-else :key="index + '-demandLatestTime'" :text="text" @change="onCellChange(record, 'demandLatestTime', $event)"></EditableDate>
          </template>
          <!-- 责任人 -->
          <span slot="demandResponsibleId" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ record.demandResponsibleName }}</span>
            <div v-else class="requiredFormItem">
              <SelectPerson :fetching="fetching" :key="index + '-demandResponsibleId'" @changeEmployeeName="changeEmployeeName" :memberList="memberList" :record="record" bindKey="demandResponsibleId"></SelectPerson>
            </div>
          </span>
  
          <!-- 风险源分析 -->
          <span slot="riskSourceAnalysis" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell :required="true" v-else :key="index + '-riskSourceAnalysis'" :text="text" @change="onCellChange(record, 'riskSourceAnalysis', $event)" :maxLength="300"></EditableCell>
          </span>
  
          <!-- 风险辨识 -->
          <span slot="riskIdentification" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell :required="true" v-else :key="index + '-riskIdentification'" :text="text" @change="onCellChange(record, 'riskIdentification', $event)" :maxLength="300"></EditableCell>
          </span>
  
          <!-- 应对措施 -->
          <span slot="solutions" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell :required="true" v-else :key="index + '-solutions'" :text="text" @change="onCellChange(record, 'solutions', $event)" :maxLength="300"></EditableCell>
          </span>
  
          <!-- 甲方认定价格 -->
          <span slot="partyARecognizePrice" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableNumber
              :min="-Infinity"
              :precision="2"
              :required="true"
              v-else
              :step="0.01"
              :key="index + '-partyARecognizePrice'"
              :text="text"
              @change="onCellChange(record, 'partyARecognizePrice', $event)"
            ></EditableNumber>
          </span>
  
          <!-- 成本 -->
          <span slot="cost" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableNumber  :min="-Infinity" :precision="2" :required="true" v-else :step="0.01" :key="index + '-cost'" :text="text" @change="onCellChange(record, 'cost', $event)"></EditableNumber>
          </span>
  
          <!-- 价差效益(元) -->
          <span slot="spreadsBenefit" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableNumber  :min="-Infinity" :precision="2" :required="true" v-else :step="0.01" :key="index + '-spreadsBenefit'" :text="text" @change="onCellChange(record, 'spreadsBenefit', $event)"></EditableNumber>
          </span>
  
          <!-- 量差效益(元)-->
          <span slot="amountBenefit" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableNumber  :min="-Infinity" :precision="2" :required="true" v-else :step="0.01" :key="index + '-amountBenefit'" :text="text" @change="onCellChange(record, 'amountBenefit', $event)"></EditableNumber>
          </span>
  
          <!-- 效益总额(元) -->
          <span slot="totalBenefit" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableNumber  :min="-Infinity" :precision="2" :required="true" v-else :step="0.01" :key="index + '-totalBenefit'" :text="text" @change="onCellChange(record, 'totalBenefit', $event)"></EditableNumber>
          </span>
  
          <!-- 效益率 -->
          <span slot="benefitRate" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableNumber  :min="-Infinity" :precision="2" :required="true" v-else :step="0.01" :key="index + '-benefitRate'" :text="text" @change="onCellChange(record, 'benefitRate', $event)"></EditableNumber>
          </span>
  
          <!-- 备注 -->
          <span slot="remark" slot-scope="text, record, index">
            <span v-if="queryInfo.pageType == 'detail'">{{ text }}</span>
            <EditableCell v-else :key="index + '-remark'" :text="text" @change="onCellChange(record, 'remark', $event)" :maxLength="300"></EditableCell>
          </span>
  
          <span slot="operation" slot-scope="text, record">
            <template>
              <a-popconfirm title="请确认是否要删除？" @confirm="() => onDelete(record)">
                <a href="javascript:;">删除</a>
              </a-popconfirm>
            </template>
          </span>
        </a-table>
        <a-button class="mt20" type="primary" @click="addRow" v-if="queryInfo.pageType !== 'detail'"> 增行 </a-button>
      </a-card>
    </div>
  </template>
  
  <script>
  import { queryPlanSubSelectDetail } from '@/api/projectManagementPlanning/projectPlanningTaskList'
  import EditableCell from '../../../projectManagementPlanning/projectPlanningTaskList/detail/components/EditableCell'
  import EditableNumber from '../../../projectManagementPlanning/projectPlanningTaskList/detail/components/EditableNumber'
  import EditableDate from '../../../projectManagementPlanning/projectPlanningTaskList/detail/components/EditableDate'
  import { getOrganizeUserListQuick } from '@/api/commons'
  
  import SelectPerson from '../../../projectManagementPlanning/projectManagementPlanningComponents/components/ProjectDesignPlanningForm/SelectPerson'
  import { planMaterialupdateByPrimaryKeySelective } from '@/api/projectManagementPlanning/projectPlanningTaskList'
  import { schemeQueryPlanSubSelectDetail, schemeUpdateByPrimaryKeySelective } from '@/api/project/plannManagement/interpenetrationPlan.js'
  
  const DEFAULT_ROW = [
    {
      name: '',
      procurementMethod: '',
      responsibleTime: '',
      productionCycle: '',
      materialLatestTime: '',
      materialResponsibleId: undefined,
      tenderLatestTime: '',
      tenderResponsibleId: undefined,
      brandLatestTime: '',
      brandResponsibleId: undefined,
      demandLatestTime: '',
      demandResponsibleId: undefined,
      riskSourceAnalysis: '',
      solutions: '',
      partyARecognizePrice: '',
      riskIdentification: '',
      cost: '', // 成本
      spreadsBenefit: '',
      amountBenefit: '',
      totalBenefit: '',
      benefitRate: '',
      remark: '',
      guid: new Date().getTime()
    }
  ]
  
  const REQUEST_KEYS = [
    'name',
    'procurementMethod',
    'responsibleTime',
    'productionCycle',
    'materialLatestTime',
    'materialResponsibleId',
    'tenderLatestTime',
    'tenderResponsibleId',
    'brandLatestTime',
    'brandResponsibleId',
    'demandLatestTime',
    'demandResponsibleId',
    'riskSourceAnalysis',
    'riskIdentification',
    'solutions',
    'partyARecognizePrice',
    'cost',
    'spreadsBenefit',
    'amountBenefit',
    'totalBenefit',
    'benefitRate'
  ]
  export default {
    name: 'ProcurementPlanning',
    data() {
      return {
        queryInfo: {
          id: '',
          pageType: ''
        },
        columns: [
          {
            title: '序号',
            width: 50,
            align: 'center',
            dataIndex: 'serial',
            scopedSlots: { customRender: 'serial' }
          },
          {
            title: '物资名称',
            width: 150,
            align: 'center',
            dataIndex: 'name',
            scopedSlots: { customRender: 'name' }
          },
          {
            title: '工作计划',
            align: 'center',
            children: [
              {
                title: '采购方式',
                width: 100,
                align: 'center',
                dataIndex: 'procurementMethod',
                scopedSlots: { customRender: 'procurementMethod' }
              },
              {
                title: '责任人及计划时间',
                width: 200,
                align: 'center',
                dataIndex: 'responsibleTime',
                scopedSlots: { customRender: 'responsibleTime' }
              },
              {
                title: '产运周期（天）',
                width: 150,
                align: 'center',
                dataIndex: 'productionCycle',
                scopedSlots: { customRender: 'productionCycle' }
              },
              {
                title: '物资进场',
                align: 'center',
                children: [
                  {
                    title: '最迟时间',
                    width: 180,
                    align: 'center',
                    dataIndex: 'materialLatestTime',
                    scopedSlots: { customRender: 'materialLatestTime' }
                  },
                  {
                    title: '责任人',
                    width: 150,
                    align: 'center',
                    dataIndex: 'materialResponsibleId',
                    scopedSlots: { customRender: 'materialResponsibleId' }
                  }
                ]
              },
              {
                title: '物资招标',
                align: 'center',
                children: [
                  {
                    title: '最迟时间',
                    width: 180,
                    align: 'center',
                    dataIndex: 'tenderLatestTime',
                    scopedSlots: { customRender: 'tenderLatestTime' }
                  },
                  {
                    title: '责任人',
                    width: 150,
                    align: 'center',
                    dataIndex: 'tenderResponsibleId',
                    scopedSlots: { customRender: 'tenderResponsibleId' }
                  }
                ]
              },
              {
                title: '品牌业主确认',
                align: 'center',
                children: [
                  {
                    title: '最迟时间',
                    width: 180,
                    align: 'center',
                    dataIndex: 'brandLatestTime',
                    scopedSlots: { customRender: 'brandLatestTime' }
                  },
                  {
                    title: '责任人',
                    width: 150,
                    align: 'center',
                    dataIndex: 'brandResponsibleId',
                    scopedSlots: { customRender: 'brandResponsibleId' }
                  }
                ]
              },
              {
                title: '需求计划编制',
                align: 'center',
                children: [
                  {
                    title: '最迟时间',
                    width: 180,
                    align: 'center',
                    dataIndex: 'demandLatestTime',
                    scopedSlots: { customRender: 'demandLatestTime' }
                  },
                  {
                    title: '责任人',
                    width: 150,
                    align: 'center',
                    dataIndex: 'demandResponsibleId',
                    scopedSlots: { customRender: 'demandResponsibleId' }
                  }
                ]
              }
            ]
          },
          {
            title: '风险源分析',
            width: 150,
            align: 'center',
            dataIndex: 'riskSourceAnalysis',
            scopedSlots: { customRender: 'riskSourceAnalysis' }
          },
          {
            title: '风险辨识',
            width: 200,
            align: 'center',
            dataIndex: 'riskIdentification',
            scopedSlots: { customRender: 'riskIdentification' }
          },
          {
            title: '应对措施',
            align: 'center',
            dataIndex: 'solutions',
            width: 200,
            scopedSlots: { customRender: 'solutions' }
          },
          {
            title: '甲方认价(元)',
            width: 150,
            // width: 72,
            align: 'center',
            dataIndex: 'partyARecognizePrice',
            scopedSlots: { customRender: 'partyARecognizePrice' }
          },
          {
            title: '成本(元)',
            width: 150,
            align: 'center',
            dataIndex: 'cost',
            scopedSlots: { customRender: 'cost' }
          },
          {
            title: '价差效益(元)',
            width: 150,
            align: 'center',
            dataIndex: 'spreadsBenefit',
            scopedSlots: { customRender: 'spreadsBenefit' }
          },
          {
            title: '量差效益(元)',
            width: 150,
            align: 'center',
            dataIndex: 'amountBenefit',
            scopedSlots: { customRender: 'amountBenefit' }
          },
          {
            title: '效益总额(元)',
            width: 150,
            align: 'center',
            dataIndex: 'totalBenefit',
            scopedSlots: { customRender: 'totalBenefit' }
          },
          {
            title: '效益率(%)',
            width: 150,
            align: 'center',
            dataIndex: 'benefitRate',
            scopedSlots: { customRender: 'benefitRate' }
          },
          {
            title: '备注',
            width: 150,
            align: 'center',
            dataIndex: 'remark',
            scopedSlots: { customRender: 'remark' }
          },
          {
            title: '操作',
            align: 'center',
            fixed: 'right',
            width: 100,
            dataIndex: 'operation',
            scopedSlots: { customRender: 'operation' }
          }
        ],
        data: [],
        memberList: [], // 接收人
        fetching: false
      }
    },
  
    props: {
      spinning: Boolean,
      baseFormInfo: {
        type: Object,
        default: () => {}
      }
    },
  
    components: { EditableCell, EditableNumber, EditableDate, SelectPerson },
  
    computed: {},
  
    watch: {
      baseFormInfo: {
        handler(val) {
          if (val.projectId) {
            this.getImplees()
          }
        },
        immediate: true
      }
    },
  
    created() {
      const { id, pageType, version = '' } = this.$route.query
      /**
       * version 不存在 就是正常入口进来的。
       * 否则 就是在V1等弹窗进来的
       */
      this.queryInfo.id = id
      this.queryInfo.pageType = pageType
      this.queryInfo.version = version
      if (this.queryInfo.pageType === 'detail') {
        this.columns.pop()
      }
      this.queryPlanSubSelectDetail()
    },
  
    mounted() {},
  
    methods: {
      // 增行
      addRow() {
        const DEFAULT_ROW_ = JSON.parse(JSON.stringify(DEFAULT_ROW))
        this.data.push({ ...[...DEFAULT_ROW_][0], guid: this.getGuid() })
      },
      // 草稿
      ProcurementPlanningSaveDrafts(formBase) {
        this.$emit('update:spinning', true)
        const query = {
          list: JSON.parse(JSON.stringify(this.data)),
          changed: this.queryInfo.pageType === 'change' ? true : false,
          schemeDetailId: this.queryInfo.id,
          status: 0,
          version: this.queryInfo.version
        }
        this.$emit('updateBasicDetail', {...formBase, schemeDetailId: this.queryInfo.id, status: 0})
        schemeUpdateByPrimaryKeySelective(query)
          .then((res) => {
            this.$emit('update:spinning', false)
            this.$message.success('保存成功')
            this.$emit('closePage');
          })
          .catch(() => {
            this.$emit('update:spinning', false)
          })
      },
      // 提交
      ProcurementPlanningSubmit(formBase) {
        let flag = true // 是否全部填写
        this.data.map((v) => {
          REQUEST_KEYS.map((k) => {
            if (v[k] === '' || v[k] == null || v[k] == undefined || (v[k] + '').replace(/\s*/g, '') == '') {
              flag = false
            }
          })
        })
        if (this.data.length === 0) {
          this.$warning({
            title: '提示',
            content: '请至少填写一行数据',
            okText: '确定'
          })
          return
        }
        if (!flag) {
          this.$warning({
            title: '提示',
            content: '请将数据填写完整',
            okText: '确定'
          })
          return
        } else {
          this.$confirm({
            title: '提交',
            content: '请确认是否要提交？',
            onOk: async () => {
              this.$emit('update:spinning', true)
              const query = {
                list: JSON.parse(JSON.stringify(this.data)),
                changed: this.queryInfo.pageType === 'change' ? true : false,
                schemeDetailId: this.queryInfo.id,
                status: 1,
                version: this.queryInfo.version
              }
              this.$emit('updateBasicDetail', {...formBase,schemeDetailId: this.queryInfo.id, status: 1})
              schemeUpdateByPrimaryKeySelective(query)
                .then((res) => {
                  this.$emit('update:spinning', false)
                  this.$message.success('提交成功')
                  this.$emit('closePage');
                })
                .catch(() => {
                  this.$emit('update:spinning', false)
                })
            },
            onCancel: () => { this.$emit('update:spinning', false)}
          })
        }
      },
      getGuid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = (Math.random() * 16) | 0
          var v = c === 'x' ? r : (r & 0x3) | 0x8
          return v.toString(16)
        })
      },
      // 删除item
      onDelete(item) {
        let arr = JSON.parse(JSON.stringify(this.data))
        arr = arr
          .map((v) => {
            if (v.guid !== item.guid) {
              return v
            }
          })
          .filter((v) => v && v.guid)
        this.data = arr
      },
      // 更新item
      onCellChange(item, dataIndex, value) {
        this.data.map((v) => {
          if (v.guid === item.guid) {
            v[dataIndex] = value
          }
        })
      },
      // 获取接收人
      getImplees() {
        this.fetching = true
        getOrganizeUserListQuick({ projectId: this.baseFormInfo.projectId }).then((res) => {
          const obj = {}
          // 去掉重复以及employeeId为空的数据
          res.data = res.data.reduce(function (item, next) {
            obj[next.employeeId] || !next.employeeId ? '' : (obj[next.employeeId] = true && item.push(next))
            return item
          }, [])
          this.memberList = res.data
          this.fetching = false
        })
      },
      // 选择接收人
      changeEmployeeName({ guid, key, id, name, phone }) {
        this.data.map((v) => {
          if (v.guid === guid) {
            if (key == 'materialResponsibleId') {
              v.materialResponsibleId = id
              v.materialResponsibleName = name
            }
            if (key == 'tenderResponsibleId') {
              v.tenderResponsibleId = id
              v.tenderResponsibleName = name
            }
            if (key == 'brandResponsibleId') {
              v.brandResponsibleId = id
              v.brandResponsibleName = name
            }
            if (key == 'demandResponsibleId') {
              v.demandResponsibleId = id
              v.demandResponsibleName = name
            }
          }
        })
      },
      // 获取详情
      queryPlanSubSelectDetail() {
        this.$emit('update:spinning', true)
        const query = {
            schemeDetailId: this.queryInfo.id,
            latestData: true
        }
        if (this.queryInfo.version) {
            query.latestData = false
            query.version = this.queryInfo.version
        }
        schemeQueryPlanSubSelectDetail(query)
          .then((res) => {
            if (res.data && res.data.length) {
              res.data.map((v) => (v.guid = this.getGuid()))
              this.data = res.data
            } else {
              const DEFAULT_ROW_ = JSON.parse(JSON.stringify(DEFAULT_ROW))
              this.data = [...DEFAULT_ROW_]
            }
            this.$emit('update:spinning', false)
          })
          .catch(() => {
            this.$emit('update:spinning', false)
          })
      }
    }
  }
  </script>
  <style lang='less' scoped>
  </style>